﻿package com.thorqq.magictimer.timeLoop;

import java.util.Calendar;

import com.thorqq.magictimer.R;
import com.thorqq.magictimer.core.ChildView;
import com.thorqq.magictimer.core.ChildViewParent;
import com.thorqq.magictimer.core.TLoopPolicy;
import com.thorqq.magictimer.util.Util;
import com.thorqq.magictimer.widget.WheelView.NumericWheelAdapter;
import com.thorqq.magictimer.widget.WheelView.OnWheelChangedListener;
import com.thorqq.magictimer.widget.WheelView.WheelView;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ScrollView;

public class ChildViewLoopDay extends ChildView
{
    private ChildViewParent mParent;
    private TLoopPolicyDay mDayLoopPolicy;
    private Context mContext;
    private LayoutInflater mInflater;

    private EditText mEtMaxCount;
    private EditText mEtLoopDays;
    private Button   mBtnDayMask;
    private CheckBox mCBInfinity;
    private Button   mBtnToday;

    private WheelView mWvYear;
    private WheelView mWvMonth;
    private WheelView mWvDay;
    
    private NumericWheelAdapter mNumericWheelAdapter28 = new NumericWheelAdapter(1,28);
    private NumericWheelAdapter mNumericWheelAdapter29 = new NumericWheelAdapter(1,29);
    private NumericWheelAdapter mNumericWheelAdapter30 = new NumericWheelAdapter(1,30);
    private NumericWheelAdapter mNumericWheelAdapter31 = new NumericWheelAdapter(1,31);
    private NumericWheelAdapter[] NumericWheelAdapterArray = new NumericWheelAdapter[]{
            mNumericWheelAdapter31,
            mNumericWheelAdapter28,
            mNumericWheelAdapter31,
            mNumericWheelAdapter30,
            mNumericWheelAdapter31,
            mNumericWheelAdapter30,
            mNumericWheelAdapter31,
            mNumericWheelAdapter31,
            mNumericWheelAdapter30,
            mNumericWheelAdapter31,
            mNumericWheelAdapter30,
            mNumericWheelAdapter31
    };

    boolean[] mCheckedItems = null;
    boolean[] mTmpCheckedItems = null;

    final static private int BASE_YEAR = 2012;
    final static private int BASE_MONTH = 1;
    final static private int BASE_DAY = 1;

    public ChildViewLoopDay(Context context, TLoopPolicy policy)
    {
        mContext = context;
        mDayLoopPolicy = (TLoopPolicyDay) policy;
    }

    @Override
    public void updateLayout()
    {
        mWvYear.setCurrentItem(mDayLoopPolicy.getStartDate().get(Calendar.YEAR) - BASE_YEAR);
        mWvMonth.setCurrentItem(mDayLoopPolicy.getStartDate().get(Calendar.MONTH)+1-BASE_MONTH);
        mWvDay.setCurrentItem(mDayLoopPolicy.getStartDate().get(Calendar.DATE) - BASE_DAY);
        
        mEtLoopDays.setText(Util.intToStr(mDayLoopPolicy.getLoopDays()));
        
        if(mDayLoopPolicy.getMaxCount() == TimerCalculator.INFINITY_COUNT)
        {
            mCBInfinity.setChecked(true);
            mEtMaxCount.setEnabled(false);
            mEtMaxCount.setText("1");
        }
        else if(mDayLoopPolicy.getMaxCount() >= 1)
        {
            mCBInfinity.setChecked(false);
            mEtMaxCount.setEnabled(true);
            mEtMaxCount.setText(Util.intToStr(mDayLoopPolicy.getMaxCount()));
        }
        else
        {
            mCBInfinity.setChecked(false);
            mEtMaxCount.setEnabled(true);
            mEtMaxCount.setText("1");
        }
    
        int len = mDayLoopPolicy.getDayMask().length;
        char[] arr = mDayLoopPolicy.getDayMask();
        mCheckedItems = new boolean[len];
        for(int i = 0; i < len; i++)
        {
            mCheckedItems[i] = (arr[i] == '1' ? true : false);
        }

    }

    @Override
    protected void doSetParentScrollView(ScrollView parentScrollView)
    {
        mWvYear.setParentScrollView(parentScrollView);
        mWvMonth.setParentScrollView(parentScrollView);
        mWvDay.setParentScrollView(parentScrollView);
    }

    @Override
    protected void registerListener()
    {        
        OnWheelChangedListener wheelListener = new OnWheelChangedListener() {
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                int year = mWvYear.getCurrentItem() + BASE_YEAR;
                int month = mWvMonth.getCurrentItem()+ BASE_MONTH;
                int day = mWvDay.getCurrentItem() + BASE_DAY;
                
                //动态更新“日”Wheel
                int oldItemCnt = mWvDay.getAdapter().getItemsCount();
                int newItemCnt = NumericWheelAdapterArray[month-1].getItemsCount();
                //闰年
                if(year%400 == 0 || (year%4 == 0 && year%100 != 0))
                {
                    if(month == 2)
                    {
                        newItemCnt = 29;
                    }
                }

                if(newItemCnt != oldItemCnt)
                {
                    if(newItemCnt == 29)
                    {
                        mWvDay.setAdapter(mNumericWheelAdapter29);
                    }
                    else
                    {
                        mWvDay.setAdapter(NumericWheelAdapterArray[month-1]);
                    }
                    mWvDay.setCurrentItem(mWvDay.getCurrentItem(), true);
                }
                
                mDayLoopPolicy.getStartDate().set(Calendar.YEAR,  year);
                mDayLoopPolicy.getStartDate().set(Calendar.MONTH, month - 1);
                mDayLoopPolicy.getStartDate().set(Calendar.DATE,  day);
            }
        };

        mWvYear.addChangingListener(wheelListener);
        mWvMonth.addChangingListener(wheelListener);
        mWvDay.addChangingListener(wheelListener);
        
        mBtnToday.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                Calendar today = Calendar.getInstance();
                int year = today.get(Calendar.YEAR);        // 2013年
                int month = today.get(Calendar.MONTH) + 1;  // 从0开始。例如：0表示1月
                int day = today.get(Calendar.DAY_OF_MONTH); // 从1开始。1就表示1号

                mWvYear.setCurrentItem(year - BASE_YEAR, true);
                mWvMonth.setCurrentItem(month - BASE_MONTH, true);
                //这里不能启动动画，否则会出现定位不准的问题
                mWvDay.setCurrentItem(day - BASE_DAY);
            }
        });


        mBtnDayMask.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                int days = Util.strToInt(mEtLoopDays.getText().toString());
                Util.log("days = " + days);
                if(days <= 0)
                {
                    AlertDialog.Builder builder = new Builder(mContext);
                    builder.setTitle("错误");
                    builder.setMessage("循环天数非法，请重新输入");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    builder.create().show();
                    return;
                }
                
                //多选显示的文字
                String[] arrayItems = new String[days];
                for(int i = 0; i < days; i++)
                {
                    arrayItems[i] = "第" + (i+1) + "天";
                }
                
                //哪几项要被选择
                mTmpCheckedItems = mCheckedItems.clone();
                if(mTmpCheckedItems.length != days)
                {
                    mTmpCheckedItems = new boolean[days];
                }
                
                new AlertDialog.Builder(mContext)
                        .setTitle("请选择启动日")
                        .setMultiChoiceItems(arrayItems, mTmpCheckedItems, 
                                new OnMultiChoiceClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which, boolean isChecked)
                                    {
        
                                    }
                                })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() 
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                int flag = 0;
                                for(boolean b: mTmpCheckedItems)
                                {
                                    if(b == true)
                                    {
                                        flag = 1;
                                        break;
                                    }
                                }
                                
                                if(flag == 0)
                                {
                                    displayValidDialog("没有设置启动日");
                                    return;
                                }
                                
                                mCheckedItems = mTmpCheckedItems.clone();
                                char[] dayMask = new char[mCheckedItems.length];
                                for(int i = 0; i < mCheckedItems.length; i++)
                                {
                                    dayMask[i] = (mCheckedItems[i] == true ? '1' : '0');
                                }
                                
                                mDayLoopPolicy.setDayMask(dayMask);
                                
                                mParent.dataUpdateNotify();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
            }
            
        });

        mCBInfinity.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked)
            {
                mEtMaxCount.setEnabled(!isChecked);
                if(isChecked)
                {
                    mDayLoopPolicy.setMaxCount(TimerCalculator.INFINITY_COUNT);
                }
                else
                {
                    mDayLoopPolicy.setMaxCount(Util.strToInt(mEtMaxCount.getText().toString()));
                }            }
        });
        
        mEtMaxCount.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void afterTextChanged(Editable arg0)
            {                
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
            {                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                if(mCBInfinity.isChecked())
                {
                    mDayLoopPolicy.setMaxCount(TimerCalculator.INFINITY_COUNT);
                }
                else
                {
                    mDayLoopPolicy.setMaxCount(Util.strToInt(s.toString()));
                }         
            }
            
        });

        mEtLoopDays.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void afterTextChanged(Editable arg0)
            {                
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
            {                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                mDayLoopPolicy.setLoopDays(Util.strToInt(s.toString()));
            }
            
        });
    }

    @Override
    protected void doInitLayout(ChildViewParent parent)
    {
        Util.log("init ChildViewLoopPolicyDay");
        mInflater = LayoutInflater.from(mContext);
        mView = mInflater.inflate(R.layout.loop_item_child_day, null);
        mParent = parent;

        mEtMaxCount = (EditText) mView.findViewById(R.id.editTextMaxCount);
        mEtLoopDays = (EditText) mView.findViewById(R.id.editTextLoopDays);
        mBtnDayMask = (Button) mView.findViewById(R.id.btnDayMask);
        mCBInfinity = (CheckBox) mView.findViewById(R.id.checkBoxInfinity);
        mBtnToday   = (Button) mView.findViewById(R.id.btnToday);

        mWvYear = (WheelView) mView.findViewById(R.id.year);
        mWvYear.setAdapter(new NumericWheelAdapter(2012, 2020));
        mWvYear.setCyclic(true);

        mWvMonth = (WheelView) mView.findViewById(R.id.month);
        mWvMonth.setAdapter(new NumericWheelAdapter(1, 12));
        mWvMonth.setCyclic(true);

        mWvDay = (WheelView) mView.findViewById(R.id.day);
        mWvDay.setAdapter(mNumericWheelAdapter31);
        mWvDay.setCyclic(true);
    }

    //参数校验错误提示对话框
    private void displayValidDialog(String validInfo)
    {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("错误");
        builder.setMessage(validInfo);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();
    }

    @Override
    protected void doSetTag(Object object)
    {
        if(object instanceof TLoopPolicyDay)
        {
            mDayLoopPolicy = (TLoopPolicyDay)object;
        }
    }

    @Override
    public void onClose()
    {
        
    }

}
